#include "DoubleLinkvoid.h"

DoubleLinkList::DoubleLinkList():FreePtr(nullptr),ShowPtr(nullptr)
{
    head= new Node(0);
    tail= head;
}

void DoubleLinkList::InsertTail(const ElementType &element)
{
    Node *newNode= new Node(element);
    tail->next= newNode;
    newNode->prev= tail;
    tail= newNode;
    size++;
}

void DoubleLinkList::InsertHead(const ElementType &element)
{
    Node *newNode= new Node(element);
    newNode->next=head->next;
    newNode->prev=head;
    head->next=newNode;
    if(size!=0)
        newNode->next->prev=newNode;
    else
        tail=newNode;
    size++;
}

void DoubleLinkList::InsertByIndex(int index, const ElementType element)
{
    Node *travelPoint= head;
    for(int i=0; i<index; i++)
    {
        travelPoint= travelPoint->next;
    }
    Node *newNode= new Node(element);
    newNode->next= travelPoint->next;
    newNode->prev= travelPoint;
    travelPoint->next= newNode;
    if(index != size)
        newNode->next->prev=newNode;
    else
        tail=newNode;

    size++;
}

void DoubleLinkList::RemoveByIndex(int index)
{
    if(index<0||index>=size)
    {
        std::cout<<"非法的删除位置"<<std::endl;
        return;
    }
    Node *travelPoint= head;
    for(int i=0; i<index; i++)
    {
        travelPoint= travelPoint->next;
    }
    Node *freeNode= travelPoint->next;


    if(index!=size-1)
    {
        travelPoint->next=freeNode->next;
        freeNode->next->prev=travelPoint;
        
    }else{
        travelPoint->next = nullptr;
        tail= travelPoint;
    }
    delete freeNode;
    size--;
}

void DoubleLinkList::RemoveByElement(const ElementType &element)
{
    Node *travelPoint= head;
    while(travelPoint->next != nullptr)
    {
        if(travelPoint->next->data== element)
        {
            Node *freeNode= travelPoint->next;
            if(freeNode->next!= nullptr)
            {
            travelPoint->next=freeNode->next;
            freeNode->next->prev=travelPoint;
            }else{
                travelPoint->next = nullptr;
                tail= travelPoint;
            }
            delete freeNode;
            size--;
        }
        else
            travelPoint= travelPoint->next;
    }

}

DoubleLinkList::~DoubleLinkList()
{
    //链表不能回头
    // if(FreePtr)
    // FreePtr(head);
    while(head != nullptr)
    {
        Node *nextNode= head->next; //记下下一个节点
        delete head;
        head= nextNode; //结点往后走
    }
}

void DoubleLinkList::show()
{
    std::cout<<"size:"<<size<<std::endl;
    //遍历指针
    Node *travelPoint = head->next;
    while(travelPoint != nullptr)
    {
        ShowPtr(travelPoint->data);
        travelPoint= travelPoint->next;
    }
    std::cout<<std::endl;

    travelPoint= tail;
    while(travelPoint != head)
    {
        ShowPtr(travelPoint->data);
        travelPoint= travelPoint->prev;
    }
    std::cout<<std::endl;
}

